<template>
    <div class="data-management-container">
        <global-search @submitSearch="submitSearch" :showDep="false" :showLast="false" class="global-tool-search">
            <template slot="other-form">
                <el-form-item label="文件名">
                    <el-input v-model="searchForm.keyword" class="keyword-input" size="small"
                              placeholder="请输入文件名"></el-input>
                </el-form-item>
            </template>
        </global-search>
        <div class="page-content">
            <div class="head">
                <h3>导入文件列表</h3>
                <btn-group :showBtn="showBtn" @toUpload="showDialog" :code="{uploadCode: 100002000001, exportCode: 100003000004}" @toExport="toExport"/>
            </div>
            <el-table
                ref="tableData"
                :data="tableData"
                row-key="id"
                tooltip-effect="light"
                border
                :max-height="tableHeight"
                class="data-table"
                @sort-change="sortChange"
                @selection-change="handleSelectionChange">
                <el-table-column
                    type="selection"
                    align="center"
                    :reserve-selection="true"
                    width="30">
                </el-table-column>
                <el-table-column
                    label="序号"
                    type="index"
                    align="center"
                    width="40">
                </el-table-column>
                <el-table-column
                    prop="orgName"
                    label="机构名称"
                    min-width="120"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="fileName"
                    label="文件名"
                    min-width="160"
                    sortable="custom"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span class="to-child-page" @click="toMRList(scope.row)">{{scope.row.fileName}}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="total"
                    label="病案数"
                    align="center"
                    min-width="80"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="defect"
                    label="缺陷病案数"
                    align="center"
                    min-width="90"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="defectRate"
                    label="缺陷率"
                    min-width="90"
                    align="center"
                    sortable="custom"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        {{scope.row.defectRate}}{{scope.row.defectRate ? '%' : ''}}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="nationAvgScore"
                    label="平均得分"
                    min-width="80"
                    align="center"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="uploadDate"
                    label="导入时间"
                    align="center"
                    min-width="140"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="uploadUser"
                    label="导入人"
                    min-width="70"
                    align="center"
                    sortable="custom"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="status"
                    label="状态"
                    min-width="160"
                    align="center"
                    sortable="custom"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-progress v-if="scope.row.status === '2' || scope.row.status === '5'" :text-inside="true" :stroke-width="16" :percentage="scope.row.progrossValue"></el-progress>
                        <div v-else-if="scope.row.status === '3'">
                            <span class="status-green">审核通过({{scope.row.noted}})</span>
                            <span class="status-red"> 驳回({{scope.row.reject}})</span>
                        </div>
                        <span v-else :class="{
                        'status-green': scope.row.status === '4',
                        'status-yellow': ['2', '3', '5'].includes(scope.row.status),
                        'status-red': ['1'].includes(scope.row.status),
                        'status-gray': ['0'].includes(scope.row.status)}">
                            {{scope.row.status | getPackageStatus}}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="tip"
                    label="导入提示"
                    min-width="90"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    label="操作"
                    min-width="150"
                    align="center"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                        <el-button type="text" size="small" v-if="scope.row.status === '1' && scope.row.total > 0" @click="toQC(scope.row)" v-auth="{code: 100002000001}">质控</el-button>
                        <el-button type="text" size="small" v-if="scope.row.status === '0' || scope.row.status === '1'" @click="showDialog(scope.$index, scope.row)" v-auth="{code: 100002000001}">重新导入</el-button>
                        <el-button type="text" size="small" v-if="scope.row.status === '1' || isSystemUser" @click="deleteRow(scope.$index, scope.row)" v-auth="{code: 100002000002}">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="tableData.length > 0" :total="total" :page.sync="currentPage" :limit.sync="pageSize"
                        @pagination="changePage"/>
            <el-dialog
                title="导入文件"
                :visible.sync="dialogVisible"
                :close-on-click-modal="false"
                width="30%"
                center
                :before-close="handleClose">
                <div class="content">
                    <div class="template-box">
                        <div class="tips">
                            <p><i class="el-icon-warning"></i><span>提示</span></p>
                            <el-button type="text" size="small" @click="downloadTemplate" icon="el-icon-download">下载模板
                            </el-button>
                        </div>
                        <p><span></span>支持卫统4、HQMS、公立医院绩效考核3种格式导入</p>
                        <p><span></span>支持文件格式：.xls、.xlsx、.dbf、.csv</p>
                        <p><span></span>单文件大小不超过100M，文件数量不超过5个</p>
                    </div>
                    <upload-file
                        :drag="true"
                        :limit="limit"
                        :isdbf="true"
                        :iscsv="true"
                        accept=".xls,.xlsx,.dbf,.csv"
                        :noPrompt="true"
                        :fileList="fileList"
                        @removeFile="removeFile">
                    </upload-file>
                </div>
                <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose" size="small">取 消</el-button>
                <el-button type="primary" @click="submitFileList" size="small">确 定</el-button>
            </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import {
        getDataPackage,
        uploadMultipleFiles,
        uploadSingleFile,
        downloadPackageList,
        removePackage,
        reQC
    } from '@/api/importMR'
    import Pagination from '@/components/Pagination'
    import {getSortString, viewInfoMonth} from '@/utils/filters'
    import * as signalR from '@microsoft/signalr'
    import BtnGroup from '@/components/BtnGroup'
    import uploadFile from '@/components/Upload'
    import FileSaver from 'file-saver'
    import ExcelJS from 'exceljs'

    export default {
        name: 'Dashboard',
        data () {
            return {
                // 显示按钮
                showBtn: ['toUpload', 'toExport'],
                // 当前选中
                activeName: 'package',
                // 文件名
                searchForm: {
                    keyword: ''
                },
                // 列表数据
                tableData: [],
                // 排序字段
                sortMap: {},
                // 选中的数据
                multipleSelection: [],
                // 上传数量限制
                limit: 5,
                // 数据总数
                total: 0,
                // 当前页
                currentPage: 1,
                // 每页数量
                pageSize: 20,
                // 表格高度
                tableHeight: 107,
                // 是否显示上传弹框
                dialogVisible: false,
                // 上传的文件
                fileList: [],
                // 单文件上传id
                fileDataId: '',
                // 排序方式
                sortType: '',
                // 全局搜索内容，用于翻页等不传参时使用数据
                globalForm: {},
                // 是否显示科室
                showDep: false,
                // 使用储存的数据，不去请求
                useStore: false,
                // 连接srg
                connection: null,
                // 导出的全部数据
                allexportData: [],
                // 是否是系统机构
                isSystemUser: false
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStore = this.$route.query.tags === 'tags'
            let height = document.documentElement.clientHeight - 274 - 10 - 78 - 32
            this.tableHeight = height > 107 ? height : 107
            this.initPage()
            this.joinSRG()
            this.isSystemUser = this.getLocalStorage('userMechanism', 'name') === '系统机构'
        },
        mounted () {
            window.onresize = () => {
                // 274=其他元素高度60+50+61+48+55 10=距离底部边距 78=分页组件高度
                let height = document.documentElement.clientHeight - 274 - 10 - 78 - 32
                this.tableHeight = height > 107 ? height : 107
            }
        },
        methods: {
            viewInfoMonth,
            /**
             * 连接srg
             */
            joinSRG () {
                let hubUrl = window.location.href.includes('localhost') ? 'http://192.168.0.50/mc/commandhub' : '/mc/commandhub'
                let connection = new signalR.HubConnectionBuilder().withAutomaticReconnect().withUrl(hubUrl).build()
                connection.start().catch()
                connection.on('broadcast', (msg) => {
                    let kind = msg.kind
                    let body = JSON.parse(msg.body)
                    if (kind === 0) {
                        this.tableData.forEach(item => {
                            if (item.packageID === body.packageID) {
                                item.orgName = body.pack.orgName
                                item.fileName = body.pack.fileName
                                item.total = body.pack.total
                                item.defect = body.pack.defect
                                item.defectRate = body.pack.defectRate
                                item.nationAvgScore = body.pack.nationAvgScore
                                item.uploadDate = body.pack.uploadDate
                                item.uploadUser = body.pack.uploadUser
                                item.status = body.pack.status
                                item.tip = body.pack.tip
                                item.noted = body.pack.noted
                                item.progrossValue = body.progressBar
                            }
                        })
                    }
                })
            },
            /**
             * 初始化页面参数
             */
            initPage () {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                this.currentPage = query.pageIndex || 1
                this.pageSize = query.pageSize || 20
                this.searchForm.keyword = query.keyword
                this.sortType = query.orderBy
            },
            /**
             * 翻页
             */
            changePage () {
                this.submitSearch()
            },
            /**
             * 提交查询
             * @param form 筛选条件
             */
            submitSearch (form) {
                let data = form || this.globalForm
                this.globalForm = data
                let params = {
                    pageSize: this.pageSize,
                    pageIndex: this.currentPage,
                    orderBy: this.sortType,
                    keyword: this.searchForm.keyword,
                    start: data.start,
                    end: data.end,
                    orgId: data.orgId,
                    department: data.department,
                    departmentName: data.departmentName,
                    coder: data.coder,
                    isLast: data.isLast
                }
                this.tableData = []
                this.setGetStore(this.$route.name, params)
                let packageParams = {
                    orgId: params.orgId,
                    start: params.start,
                    end: params.end,
                    pageSize: this.pageSize,
                    pageIndex: this.currentPage,
                    orderBy: this.sortType,
                    keyword: this.searchForm.keyword
                }
                this.getPackageList(packageParams)
            },
            /**
             * 选中事件
             */
            handleSelectionChange (val) {
                this.multipleSelection = val
            },
            /**
             * 获取病案包
             */
            getPackageList (params) {
                if (!params.orderBy) params.orderBy = '`uploadDate` desc'
                if (this.getSession(this.$route.name, 'getDataPackage') && this.useStore) {
                    this.useStore = false
                    let res = this.getSession(this.$route.name, 'getDataPackage')
                    if (res.code.toString() === '200') {
                        this.tableData = res.data.rows
                        this.sortMap = res.data.maps
                        this.total = res.data.total
                    }
                } else {
                    getDataPackage(params).then(res => {
                        this.useStore = false
                        this.setSession(this.$route.name, {getDataPackage: res})
                        if (res.code.toString() === '200') {
                            this.tableData = res.data.rows
                            this.sortMap = res.data.maps
                            this.total = res.data.total
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            },
            /**
             * 关闭前
             */
            handleClose () {
                if (this.fileList.length > 0) {
                    this.$confirm('还未上传，是否关闭？')
                        .then(() => {
                            this.closeDialog()
                        })
                        .catch(() => {})
                } else {
                    this.closeDialog()
                }
            },
            /**
             * 关闭弹窗
             */
            closeDialog () {
                this.fileList = []
                this.dialogVisible = false
            },
            /**
             * 显示上传弹框
             * @param index 索引
             * @param row 行数据
             */
            showDialog (index, row) {
                this.limit = row ? 1 : 5
                this.fileDataId = row ? row.packageID : ''
                this.fileList = []
                this.dialogVisible = true
            },
            /**
             * 下载模板
             */
            downloadTemplate () {
                window.location.href = '/static/卫统4.xlsx'
            },
            /**
             * 删除文件
             * @param uid 要删除的文件
             */
            removeFile (uid) {
                let index = this.fileList.findIndex(item => {
                    return item.uid === uid
                })
                if (index !== -1) {
                    this.fileList.splice(index, 1)
                }
            },
            /**
             * 提交上传文件
             */
            submitFileList () {
                if (this.fileList.length === 0) {
                    this.$message.warning('请先上传文件')
                    return false
                } else {
                    let form = new FormData()
                    for (let i = 0; i < this.fileList.length; i++) {
                        form.append('file', this.fileList[i].raw, this.fileList[i].raw.name)
                    }
                    if (this.fileDataId === '') {
                        // 多文件
                        uploadMultipleFiles(form).then(res => {
                            if (res.code.toString() === '200') {
                                if (this.activeName === 'package') {
                                    this.submitSearch()
                                }
                                this.closeDialog()
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                    } else {
                        // 单文件
                        form.append('id', this.fileDataId)
                        uploadSingleFile(form, this.fileDataId).then(res => {
                            if (res.code.toString() === '200') {
                                if (this.activeName === 'package') {
                                    this.submitSearch()
                                }
                                this.closeDialog()
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                    }
                }
            },
            /**
             * 导出文件
             */
            toExport () {
                this.toExportPackage()
            },
            /**
             * 导出病案包
             */
            toExportPackage () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                if (this.getSelectId()) {
                    params.idList = this.getSelectId('package')
                } else {
                    params.idList = []
                }
                if (!params.orderBy) params.orderBy = '`uploadDate` desc'
                this.$store.dispatch('UpdateLoadingText', '0%')
                this.$store.dispatch('UpdateIsExport', true)
                this.$store.dispatch('UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequest(params)
            },
            /**
             * 发送请求
             * @param params 请求参数
             */
            sendRequest (params) {
                let allIndex = Math.ceil(this.total / 1000)
                downloadPackageList(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data)
                        if (params.pageIndex < allIndex) {
                            this.sendRequest({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataList('病案包列表', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('UpdateIsExport', false)
                        this.$store.dispatch('UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 导出excel表头
             */
            getHeader () {
                return [{
                    header: '序号', key: 'index', width: 10
                }, {
                    header: '机构名称', key: 'orgName', width: 20
                }, {
                    header: '文件名', key: 'fileName', width: 32
                }, {
                    header: '病案数', key: 'total', width: 16
                }, {
                    header: '缺陷病案数', key: 'defect', width: 16
                }, {
                    header: '缺陷率', key: 'defectRate', width: 16
                }, {
                    header: '平均得分', key: 'nationAvgScore', width: 16
                }, {
                    header: '导入时间', key: 'uploadDate', width: 24
                }, {
                    header: '导入人', key: 'uploadUser', width: 10
                }, {
                    header: '状态', key: 'status', width: 32
                }, {
                    header: '导入提示', key: 'tip', width: 24
                }]
            },
            /**
             * 导出列表excel
             */
            exportDataList (name, data) {
                let workbook = new ExcelJS.Workbook()
                workbook.creator = 'lyliang'
                workbook.views = [{
                    x: 0,
                    y: 0,
                    firstSheet: 0,
                    activeTab: 1,
                    visibility: 'visible'
                }]
                let worksheet = workbook.addWorksheet('Sheet1')
                worksheet.columns = this.getHeader()
                for (let i = 0; i < data.length; i++) {
                    data[i].index = i + 1
                    data[i].defectRate = data[i].defectRate ? data[i].defectRate + '%' : data[i].defectRate
                    if (data[i].status === '3') {
                        data[i].status = `审核通过(${data[i].noted}) 驳回(${data[i].reject})`
                    } else {
                        data[i].status = this.$options.filters['getPackageStatus'](data[i].status)
                    }
                    worksheet.addRow(data[i])
                    let rate = parseInt((i + 1) / data.length * 0.03 * 100 + 95) + '%'
                    this.$store.dispatch('UpdateLoadingText', rate)
                }
                worksheet.getColumn('index').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('total').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('defect').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('defectRate').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('nationAvgScore').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('uploadDate').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('uploadUser').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                worksheet.getColumn('status').alignment = {wrapText: true, vertical: 'middle', horizontal: 'center'}
                workbook.xlsx.writeBuffer().then(data => {
                    this.$store.dispatch('UpdateLoadingText', '99%')
                    let blob = new Blob([data], {type: 'EXCEL_TYPE'})
                    FileSaver.saveAs(blob, `${this.parseTime(new Date().getTime())} ${name}.xlsx`)
                    this.$store.dispatch('UpdateLoadingText', '100%')
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                })
            },
            /**
             * 获取选中id
             */
            getSelectId (name) {
                let arr = []
                if (this.multipleSelection.length) {
                    this.multipleSelection.forEach(item => {
                        if (name) {
                            arr.push(item.packageID)
                        } else {
                            arr.push(item.medicalRecordID)
                        }
                    })
                    return arr
                } else {
                    return false
                }
            },
            /**
             * 排序修改
             * @param colData.prop 排序参数
             * @param colData.order 正序倒序 ascending 升序 descending 降序 null 不排序默认
             */
            sortChange (colData) {
                this.sortType = getSortString(colData, this.sortMap)
                this.tableData = []
                this.currentPage = 1
                this.submitSearch()
            },
            /**
             * 删除数据
             * @param index 索引
             * @param row 行数据
             */
            deleteRow (index, row) {
                let text = `你确定删除病案包"${row.fileName}"文件吗?删除后将不能恢复，请谨慎操作!`
                this.$confirm(text, '删除病案包提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    let params = {
                        id: row.packageID
                    }
                    removePackage(params).then(res => {
                        if (res.code.toString() === '200') {
                            this.$message.success('删除成功!')
                            this.submitSearch()
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                })
            },
            /**
             * 前往病案包列表数据
             * @param row 行数据
             */
            toMRList (row) {
                let data = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                let params = {
                    ...data,
                    packageID: row.packageID,
                    pageIndex: 1,
                    department: '',
                    departmentName: '',
                    // 下钻页面不需要时间
                    yearMonth: '',
                    isLast: true
                }
                this.$store.dispatch('search/coverSearchFormItem', {
                    pageName: 'ImportMRListIndex',
                    query: params
                })
                this.$router.push({name: 'ImportMRListIndex'})
            },
            /**
             * 重新质控
             * @param row 行数据
             */
            toQC (row) {
                reQC(row.packageID).then(res => {
                    if (res.code.toString() === '200') {
                        this.$message.success('操作成功')
                        this.submitSearch()
                    } else {
                        this.$message.error(res.message)
                    }
                }).catch(() => {
                    this.$message.success('操作失败')
                })
            }
        },
        components: {
            BtnGroup,
            Pagination,
            uploadFile
        },
        filters: {
            getStatus (val) {
                switch (val) {
                case 0:
                    return '未审核'
                case 1:
                    return '已审核'
                case 2:
                    return '驳回'
                }
            },
            getPackageStatus (val) {
                switch (val) {
                case '0':
                    return '未审核'
                case '1':
                    return '导入失败'
                case '2':
                    return '排队中'
                case '3':
                    return '审核中'
                case '4':
                    return '全部通过'
                case '5':
                    return '质控中'
                }
            }
        },
        beforeDestroy () {
            this.connection = null
            window.onresize = null
        }
    }
</script>

<style lang="scss" scoped>
    .data-management-container {
        height: calc(100% - 10px);
        .page-content {
            background: #fff;
            padding: 0 10px;
            height: calc(100% - 54px);
        }
        .head {
            display: flex;
            justify-content: space-between;
            align-items: center;
            h3 {
                font-size: 16px;
                color: #000;
                font-weight: 600;
                line-height: 48px;
            }
        }
        .data-table {
            width: 100%;
        }
    }
    .noted-doubt {
        margin: 0;
    }

    /deep/ .el-dialog {
        min-width: 600px;
        .el-dialog__body {
            padding: 10px;
            .content {
                width: 90%;
                margin: 0 auto;
                .template-box {
                    margin: 0 auto 20px;
                    background: #e7f8ff;
                    border: 1px solid #91dfff;
                    border-radius: 5px;
                    padding: 0 10px;
                    .tips {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        i {
                            margin-right: 5px;
                            color: #108EE9;
                        }
                    }
                    & > p {
                        span {
                            display: inline-block;
                            width: 5px;
                            height: 5px;
                            background: #000;
                            border-radius: 50%;
                            margin-bottom: 3px;
                            margin-right: 4px;
                        }
                        margin: 0;
                        line-height: 1.6;
                    }
                }
            }
        }
        .el-dialog__footer {
            text-align: right;
        }
    }
</style>
